﻿using AutoMapper;
using BW.MesProject.Public.Domain.RBAC;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using BW.MesProject.WareHouse.Infrastructure;
using BW.MesProject.WareHouse.Infrastructure.Dto.Input;
using BW.MesProject.WareHouse.Infrastructure.Dto.OutPut;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.WareHouse.Application
{
    /// <summary>
    /// 库位
    /// </summary>
    public class LocationServices : ILocationServices
    {
        private readonly IBaseRepository<LocationModel> _Location;
        private readonly IBaseRepository<ShelvesModel> _Shelves;
        private readonly IBaseRepository<EMPModel> _Emp;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="Location">库位仓储</param>
        /// <param name="Shelves">货架/库区仓储</param>
        /// <param name="EmpModel">员工仓储</param>
        /// <param name="mapper">AutoMapper</param>
        public LocationServices(IBaseRepository<LocationModel> Location, IBaseRepository<ShelvesModel> Shelves, IBaseRepository<EMPModel> EmpModel, IMapper mapper)
        {
            _Location = Location;
            _Shelves = Shelves;
            _Emp = EmpModel;
            this._mapper = mapper;
        }
        /// <summary>
        /// 新增库位
        /// </summary>
        /// <param name="locationModel">库位信息</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> AddLocation(LocationModel locationModel)
        {
            try
            {
                //判断库位编码，名称，所属货架/库区是否为空
                if (string.IsNullOrEmpty(locationModel.Locationid) || string.IsNullOrEmpty(locationModel.Locationname) || string.IsNullOrEmpty(locationModel.SHId.ToString()))
                { 
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "请检查库位的编号、名称、仓库是否为空"
                    };
                }
                var model = _Location.GetValue(x => x.Locationid == locationModel.Locationid);
                if (model != null && !string.IsNullOrEmpty(model.Locationid))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "库位编号重复，请重新检查修改！！！"
                    };
                }
                model = _Location.GetValue(x => x.Locationname == locationModel.Locationname);
                if (model != null && !string.IsNullOrEmpty(model.Locationname))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "库位名称重复，请重新检查修改！！！"
                    };
                }
                
                locationModel.Lid = YitIdHelper.NextId();
                
                //添加
                var models = _mapper.Map<LocationModel>(locationModel);

                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Message = "添加成功",
                    Data = _Location.Add(locationModel),
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"添加库位时发生异常: {ex.Message}");
                
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"添加失败: {ex.Message}",
                    Data = 0,
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 删除库位
        /// </summary>
        /// <param name="Id">库位主键ID</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> DeleteLocation(long Id)
        {
            // 参数验证
            if (Id == 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "无效的库位ID",
                    Data = 0,
                    TotalCount = 0
                };
            }

            try
            {
                // 根据id查询库位信息
                var model = _Location.GetValue(x => x.Lid == Id);

                // 检查是否存在
                if (model == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "未找到指定的库位信息",
                        Data = 0,
                        TotalCount = 0
                    };
                }

                // 删除前检查是否有关联的其他信息
                // TODO: 如果有其他关联表，需要检查是否有关联数据

                // 执行删除操作
                int result = _Location.Delete(model);

                if (result > 0)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Success,
                        Message = "删除成功",
                        Data = result,
                        TotalCount = 0
                    };
                }
                else
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "删除失败",
                        Data = 0,
                        TotalCount = 0
                    };
                }
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"删除库位时发生异常: {ex.Message}");
                
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"删除失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 查询库位
        /// </summary>
        /// <returns>库位列表</returns>
        public ApiResult<List<LocationOut>> GetLocation(QryInput qryInput)
        {
            try
            {
                int totalCount = 0;
                
                // 获取所有库位
                var list = _Location.GetAll().Where(x => x.IsDeleted == false);
                

                if (qryInput.PageSize == 0)
                {

                    list = list.OrderBy(u => u.CreatedTime).Where(x => x.IsEnable == true);
                }
                else
                {

                    // 按编码查询
                    if (!string.IsNullOrEmpty(qryInput.QryID) && !string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.Locationid.Contains(qryInput.QryID) && x.Locationname.Contains(qryInput.QryName));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryID))
                    {
                        list = list.Where(x => x.Locationid.Contains(qryInput.QryID));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.Locationname.Contains(qryInput.QryName));
                    }


                }
                // 处理结果数据
                var result = new List<LocationOut>();

                // 联表查询库区，人员名称等信息
                var query1 = list.LeftJoin<ShelvesModel>((a, b) => a.SHId == b.SHId).LeftJoin<UserModel>((a, b, c) => a.CreatedBy == c.UserId).Select((a, b, c) =>
                     new LocationOut
                     {
                         Lid = a.Lid,//主键ID
                         Locationid = a.Locationid,//库位ID
                         Locationname = a.Locationname,//库位名称
                         SHId = b.SHId,
                         Shelvesid = b.Shelvesid,//库位编码
                         Shelvesname = b.Shelvesname,//库位名称
                         Memo = a.Memo,//描述
                         EMPID = c.UserId,
                         EMPName = c.UserName,
                         CreatedBy = a.CreatedBy,
                         CreatedTime = a.CreatedTime,
                         UpdatedTime = a.UpdatedTime,
                         IsDeleted = a.IsDeleted,
                         IsEnable = a.IsEnable
                     });

                var queryList = query1?.ToList();


                // 计算总数量
                totalCount = queryList.Count();

                // 分页处理
                if (qryInput.PageSize > 0)
                {
                    queryList = queryList
                        .OrderBy(a => a.Locationid).ThenBy(x => x.CreatedTime)
                        .Skip((qryInput.PageNum - 1) * qryInput.PageSize)
                        .Take(qryInput.PageSize)
                        .ToList();
                }

                return new ApiResult<List<LocationOut>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = queryList,
                    TotalCount = totalCount,
                    PageNum = qryInput.PageNum,
                    PageSize = qryInput.PageSize
                };

            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"查询库位时发生异常: {ex.Message}");
                
                return new ApiResult<List<LocationOut>>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"查询失败: {ex.Message}",
                    Data = new List<LocationOut>(),
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 修改库位
        /// </summary>
        /// <param name="model">库位信息</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> UpdateLocation(LocationModel model)
        {
            try
            {
                //根据id查询是否有这条数据没有就修改不了
                var query = _Location.GetValue(x => x.Lid == model.Lid);
                if (query == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "修改失败，未找到指定的库位信息",
                        Data = 0,
                        TotalCount = 0
                    };
                }
                
                //保存添加人和添加时间，添加修改人和修改时间
                _Location.Update(model);
                
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "修改成功",
                    Data = 1,
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"修改库位时发生异常: {ex.Message}");
                
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 修改启用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateEnable(LocationModel model)
        {
            var IsEnable=model.IsEnable;
            //根据id修改逻辑删除为 false
             model = _Location.GetValue(x => x.Lid == model.Lid);
            model.IsEnable = IsEnable;
            var Message = string.Empty;
            if (IsEnable)
            {
                Message = "启用成功";
            }
            else
            {
                Message = "停用成功";
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = Message,
                Data = _Location.Update(model),
                TotalCount = 0
            };

        }

        /// <summary>
        /// 软删除（修改状态）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateDelete(long Id)
        {
            //根据id修改逻辑删除为 false
            var model = _Location.GetValue(x => x.Lid == Id);
            model.IsDeleted = true;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "删除成功",
                Data = _Location.Update(model),
                TotalCount = 0
            };
        }

        /// <summary>
        /// 查询表是否有该编码
        /// </summary>
        /// <param name="Locationid"></param>
        /// <returns></returns>
        public ApiResult<int> GetLocationID(string Locationid)
        {
            var model = _Location.GetValue(x => x.Locationid == Locationid);
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "成功",
                Data = 1,
                TotalCount = 0
            };

        }
    }
}
